package com.luoyuanxiangvip.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * IP工具
 * </p>
 *
 * @author luoyuanxiang <p>luoyuanxiangvip.com</p>
 * @since 2019/6/8
 */
public class IpUtil {

    /**
     * 获取真实IP
     *
     * @param request request
     * @return ip
     */
    public static String getRealIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        return checkIp(ip) ? ip : (
                checkIp(ip = request.getHeader("Proxy-Client-IP")) ? ip : (
                        checkIp(ip = request.getHeader("WL-Proxy-Client-IP")) ? ip :
                                request.getRemoteAddr()));
    }

    /**
     * 校验IP
     *
     * @param ip ip
     * @return boolean
     */
    private static boolean checkIp(String ip) {
        return !StringUtils.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip);
    }


    /**
     * 获取IP和地址
     * @param amapApiAk 高德地图apk
     * @param request request
     * @return map
     */
    public static Map<String, Object> getIpAndAddress(String amapApiAk, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>(6);
        String ip = "0:0:0:0:0:0:0:1".equals(IpUtil.getRealIp(request)) ? "118.112.75.197" : IpUtil.getRealIp(request);
        String url = "https://restapi.amap.com/v3/ip?ip=" + ip + "&output=json&key=" + amapApiAk;
        String s = RestClientUtil.get(url, "UTF-8");
        JSONObject jsonObject = JSONObject.parseObject(s);
        // ip地址
        map.put("ip", ip);
        // 省份名称
        map.put("province", jsonObject.get("province"));
        // 城市名称
        map.put("city", jsonObject.get("city"));
        // 城市的adcode编码
        map.put("adcode", jsonObject.get("adcode"));
        // 所在城市矩形区域范围
        map.put("rectangle", jsonObject.get("rectangle"));
        return map;
    }
}
